package com.exam.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.exam.util.Constants;

/**
 * 权限检查
 * 
 * @author Administrator
 * 
 */
public class AuthorityFilter implements Filter {
	private FilterConfig config;
	private static Log logger = LogFactory.getLog(AuthorityFilter.class);

	@Override
	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 获得filter参数
		String loginPage = config.getInitParameter("loginPage");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession(true);
		// 获取客户请求的页面
		String requestPath = req.getServletPath();
		logger.info("AuthorityFilter:"+requestPath);
		// 检查是否登录
		if (session.getAttribute(Constants.CURRENT_USER) == null
				&& !loginPage.equals(requestPath)) {
			request.getRequestDispatcher(loginPage).forward(request, response);
		} else {
			logger.info("pass!");
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}

}
